package com.run.serial;

import android.os.SystemClock;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public final class SerialTxDataTask implements Runnable {
    private final String TAG = "SerialTxDataTask";

    protected static long waitTime = 50;
    private SerialTxData txData;

    private long startTime = 0l;

    private SerialPort serialPort;
    private byte[] buff = new byte[SerialCommand.RECEIVE_PACK_LEN_MAX];
    private ByteBuffer mInputBuffer = ByteBuffer.wrap(buff);
    private int iDataLen;
    private InputStream mInputStream;

    protected SerialTxDataTask(@NonNull SerialTxData serialTxData, SerialPort port) {
        txData = serialTxData;
        serialPort = port;
        mInputStream = serialPort.getInputStream();
    }

    @Override
    public void run() {
        try {
            startTime = SystemClock.elapsedRealtime();
            while (SerialUtils.isSendData) {

                //send data
                SerialPkgData pkg = txData.getQueueData();
                if (pkg != null) {
                    txData.sendPackage(pkg.data);
                    txData.setQueueCache(pkg);
                }

                if (pkg != null && new String(pkg.data, StandardCharsets.UTF_8).equals("at+save")) {
                    SystemClock.sleep(1000);
                } else {
                    SystemClock.sleep(waitTime);
                }
//                if (SystemClock.elapsedRealtime() - startTime >= 1000) {
//                    break;
//                }

                //recv data
//                mInputBuffer.clear();
//                iDataLen = mInputStream.read(buff);
//                if ( iDataLen != 0 ) {
//                    String ret = new String(data, StandardCharsets.UTF_8);
//                    SerialRxData.getInstance().rxDataPackage(ret, buff, iDataLen);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
